<template>
  <div>
    <!--
    el-table 表明这是个table表格
    :data 它是这个表格要展示的数据
    style="width: 100%" 设置表格的宽度
    stripe  带斑马纹的表格
    border 带边框的表格
    -->
    <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-form-item label="名字">
        <el-input v-model="query.keyword" placeholder="名字"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getemployees">查询</el-button>
        <el-button type="primary" icon="el-icon-delete" @click="batchDelete"  size="medium">批量删除</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="add"  size="medium">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="pageInfo.rows"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <!--el-table-column 这是表示表格的列
      prop 就是你这一列要展示的数据的属性名
      label 该列的表头标题
      width  该列所占的宽度-->
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="username"
          label="姓名"
          width="100">
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          width="100">
      </el-table-column>
      <el-table-column
          prop="headImage"
          label="头像">
      </el-table-column>
      <el-table-column
          prop="age"
          label="年龄">
      </el-table-column>
      <el-table-column
          prop="department.name"
          label="部门">
      </el-table-column>
      <el-table-column label="操作">
        <!--slot-scope="scope"只对当前它所在的模板有效-->
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="mini"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--新增/修改的弹出框   :visible.sync 用来控制弹出框是关闭还是打开的  true 打开  false 关闭 -->
    <el-dialog title="新增/修改" :visible.sync="dialogFormVisible" v-loading="loading">
      <el-form :model="employee"  :rules="employeeFormRules" ref="employee">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="employee.username" auto-complete="off"></el-input>
          </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="100">
          <el-input v-model="employee.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" label-width="200">
          <el-input v-model="employee.headImage" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age" label-width="100">
          <el-input v-model="employee.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader v-model="employee.department.name"
                       :options="departmentTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
    </el-pagination>

  </div>

</template>

<script>
export default {
  data(){
    return {
      employee:{
        'id': null,
        'username': "",
        'email':  "",
        'headImage':"",
        'age':"",
       department:{
          id:"",
          name:""
        }
      },
      departmentTree: [],
      pageInfo:{
        rows: [],
        total:null
      },
      query:{
        currentPage:1,//起始页
        pageSize:10,//当前页条数
        keyword:""
      },
      selectValue:[],
      dialogFormVisible:false,
      loading:false,
      employeeFormRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入价格', trigger: 'blur'}
        ],
        age:[
          { required: true, message: '请输入房源', trigger: 'blur'}
        ]
      }
    }
  },
  methods:{
    save: function () {
      this.$refs.employee.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.loading = true;
            let para = Object.assign({}, this.employee);
            // 级联下拉框绑定后的值是数组,但是后端的parent需要的是一个对象,所以需要我们手动转一下
            if(para.parent != null){
              let array = para.parent;
              // 当用户选择多级部门以后,对于该部门而言,最后一个部门id才是它的父部门
              para.parent = {id:array[array.length-1]};
            }
            this.$http.put("/employee",para)
                .then(result => {
                  result = result.data;
                  if(result.success){
                    this.showMessage("成功","获取成功")
                    this.loading = false;
                    this.query.currentPage = 1;
                    this.getemployees();
                    this.dialogFormVisible = false;
                  }else{
                    this.showMessage("失败","获取失败")
                  }
                }).catch(result => {
              this.showMessage("取消","取消获取")
            })
          });
        }
      });
    },
    add(){
      this.employee= {
        'id': null,
        'username': "",
        'email':  "",
        'headImage':"",
        'age':"",
        department:{
          id:"",
          name:""
        }
      },
      this.dialogFormVisible=true
      this.getdepartmentTree()
    },
    getdepartmentTree(){
      this.$http.get("/department/tree")
          .then(result=>{
            result=result.data
            console.log(result)
            if (result.success){
              this.showMessage("成功","获取成功")
              this.departmentTree = result.result
            }else {
              this.showMessage("失败","获取失败")
            }
          }).catch(()=>{
        this.showMessage("取消","取消获取")
      })
    },
    handleEdit(index,row){
      this.dialogFormVisible =true
      this.employee = Object.assign({}, row);
      if(row.path != null){
        let arrays = row.path.split("/");
        let ids = [];
        for(let i=1;i<arrays.length-1;i++){
          ids.push(parseInt(arrays[i]))
        }
        this.employee.parent = ids;
      }
      //this.employeeForm.parent = [1,2];
      this.getdepartmentTree();
      this.getemployees();

    },
    batchDelete(){
      //获取选取的id
      let ids = this.selectValue.map(employee=>employee.id)
      console.log(ids)
      if(ids.length<1){//判断用户是否勾选了数据,没有则return
        this.showMessage("成功","请选择数据")
        return
      }
      this.$confirm('此操作将永久删除数据, 是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        this.$http.patch("/employee",ids)
            .then(result=>{
              result=result.data
              if (result.success){
                this.showMessage("成功","删除成功")
                this.query.currentPage=1
                this.getemployees()
              }else {
                this.showMessage("失败","删除失败")
              }
            })
      }).catch(()=>{
        this.showMessage("取消","取消删除")
      })
    },
    handleSizeChange(val){
      this.query.pageSize=val;
      this.query.currentPage=1;
      this.getemployees()
    },
    handleCurrentChange(val){//当前页
      this.query.currentPage =val
      this.getemployees()
    },
    handleDelete(index,row){
      console.log(index,row)
      let id = row.id
      this.$confirm('此操作将永久删除数据, 是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        this.$http.delete("/employee/"+row.id)
            .then(result=>{
              result=result.data
              if (result.success){
                this.showMessage("成功","删除成功")
                this.query.currentPage=1
                this.getemployees()
              }else {
                this.showMessage("失败","删除失败")
              }
            })
      }).catch(()=>{
        this.showMessage("取消","取消删除")
      })
    },
    showMessage(type,message){
      if (type=="成功"){
        this.$message({
          type:"success",
          message:message
        })
      }
      if (type=="失败"){
        this.$message({
          type:"error",
          message:message
        })
      }
      if (type=="取消"){
        this.$message({
          type:"info",
          message:message
        })
      }
    },
    handleSelectionChange(rows){
      console.log(rows)
      this.selectValue=rows//获取指定行id的数据上
    },
    getemployees(){//获取用户数据
      this.$http.post("/employee",this.query)
          .then(result=>{
            this.pageInfo = result.data.result
          })

    }
  },
  mounted() {
    this.getemployees()//回显

  }
}
</script>
